package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.manager.inst.CuccKiteOfferInstAcct;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.enums.RelType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstAcct;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.inst.change.KiteInstChange;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import edu.emory.mathcs.backport.java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 过户 是否默认账户由"否"切换为"是",删除已设置的付费关系，查回默认付费关系
 * 由"是"切换为"否",删除默认付费关系
 */
@Service
public class ChangeDefaultAcctAttrHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {

    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String offerInstId = querySceneInstService.getSceneInst(sceneInstId).getRootInstId();
        String custId = sceneInst.getCustId();
        if (KiteStringUtils.isEmpty(custId)) {
            custId = KiteWebContext.getContext().getCustId();
        }
        // 如果切换到默认账户
        if (KiteStringUtils.equals("1", value)) {
            //获取已有的付费关系
            List<KiteOfferInstAcct> offerInstAcctRels = querySceneInstService.listOfferInstAccts(custId, offerInstId);
            offerInstAcctRels = offerInstAcctRels.stream().filter(KiteOfferInstAcct -> KiteStringUtils.equals("1", KiteOfferInstAcct.getIsDefault())).collect(Collectors.toList());
            if (KiteListUtils.isNotEmpty(offerInstAcctRels)) {
                for (KiteOfferInstAcct offerInstAcct : offerInstAcctRels) {
                    //循环删除
                    operateSceneInstService.deleteOfferInstAcct(sceneInstId, offerInstAcct.getOfferObjInstRelId());
                }
            }
            // 获取实例变动记录
            List<KiteInstChange> instChangeList = querySceneInstService.listInstChanges(sceneInstId, InstType.OFFER_INST_ACCT);
            if (KiteListUtils.isNotEmpty(instChangeList)) {
                for (KiteInstChange instChange : instChangeList) {
                    if ( KiteStringUtils.isEqual(instChange.getNewValue(), ActionType.D.name())
                        && !KiteStringUtils.isEqual(instChange.getOldValue(), ActionType.A.name())) {
                        // 查找删除的付费关系
                        List<KiteOfferInstAcct> delOfferInstAccts = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.OFFER_INST_ACCT));
                        delOfferInstAccts = delOfferInstAccts.stream().filter(delOfferInstAcct -> KiteStringUtils.isEqual(ActionType.D.name(), delOfferInstAcct.getActionType().name())
                            && KiteStringUtils.isEqual(delOfferInstAcct.getOfferInstId(), offerInstId) && KiteStringUtils.isEqual(instChange.getSubInstId(), delOfferInstAcct.getInstId())).collect(Collectors.toList());
                        if (KiteListUtils.isNotEmpty(delOfferInstAccts)) {
                            for (KiteOfferInstAcct delOfferInstAcct : delOfferInstAccts) {
                                CuccKiteOfferInstAcct offerInstAcct = (CuccKiteOfferInstAcct) delOfferInstAcct;
                                offerInstAcct.setInstType(InstType.OFFER_INST_ACCT);
                                KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, offerInstId);
                                if (KiteObjectUtils.isEmpty(offerInst)) {
                                    ErrorConsts.OFFER_INST_NOT_EXIST.throwOut(offerInstId, custId);
                                }
                                // 没有账户明细关系，明细ID传销售品id
                                String offerId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getOfferId)
                                    .orElse("");
                                // 还原默认付费关系
                                operateSceneInstService
                                    .addOfferInstAcct(sceneInstId, offerInstAcct, offerInstId, RelType.OFFER_OBJ_REL_TYPE_170000,
                                        ActionType.A, KeyConsts.OFFER_ACCOUNT_ROLE, offerId);
                            }
                        }
                    }
                }
            }
        } else if (KiteStringUtils.equals("0", value)) {
            // 如果切换到非默认账户 删除默认付费关系 解决非默认账户没有保存实例，到预览页面仍然显示默认账户
            List<KiteOfferInstAcct> offerInstAcctRels = querySceneInstService.listOfferInstAccts(custId, offerInstId);
            offerInstAcctRels = offerInstAcctRels.stream().filter(KiteOfferInstAcct -> KiteStringUtils.equals("1", KiteOfferInstAcct.getIsDefault())).collect(Collectors.toList());
            if (KiteListUtils.isNotEmpty(offerInstAcctRels)) {
                for (KiteOfferInstAcct offerInstAcct : offerInstAcctRels) {
                    //循环删除
                    operateSceneInstService.deleteOfferInstAcct(sceneInstId, offerInstAcct.getOfferObjInstRelId());
                }
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
}
